// pages/upload/upload.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    poster:[],
    title:'',
    remark:'',
    progress:0,
    iscut:false,
    cutImgSrc:''
  },
  phoneVideo(){
    wx.chooseMedia({
      count: 1,
      camera: ['video'],
      maxDuration: 120,
      camera: 'back',
      sourceType: ['album', 'camera'],
      success(res) {
        var tempfiles = res.tempFiles
        console.log(tempfiles)
        this.setData({
          tempfiles
        })
      }
    })
  },
  // 上传视频
  afterRead(event) {
    // const { file } = event.detail;
    // const{fileList=[]} = this.data;
    // fileList.push({url:file.path});
    // this.setData({fileList})
    const that = this
    // that.phoneVideo()
    // let file = that.data.tempfiles
    let file = event.detail.file
    console.log(file)
    // that.setData({
    //   thumbTempFilePath:file[0].url
    // })
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let token = wx.getStorageSync('token')
    const uploadTask = wx.uploadFile({
      url: app.globalData.host+'/VideoToken/file', 
      filePath: file.url,
      name: 'file',
      header:{
        "Content-Type": "multipart/form-data",
        'accept': 'application/json',
      },
      formData: { token,file },
      success(res) {
        console.log(res)
        res = JSON.parse(res.data)
        console.log(res)
        if(res.code==5001||res.code==5000){
          wx.showToast({
            title: 'token已失效,请重新登录',
            icon:'none'
          })
          setTimeout(function(){
            wx.reLaunch({
              url: '/pages/personal/personal',
            })
          },1000)
          return
        }
        // 上传完成需要更新 fileList
        const { fileList = [] } = that.data;
        fileList.push({ ...file, url: res.data[0].set_path });
        that.setData({ fileList });
      },
    });
    uploadTask.onProgressUpdate((res)=>{
      this.setData({
        progress:res.progress
      })
      // console.log('上传进度', res.progress)
      // console.log('已经上传的数据长度', res.totalBytesSent)
      // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },
  // 上传封面前截取图片
  getcutimg(event){
    const that = this
    const { file, callback } = event.detail==undefined?that.data.file:event.detail;
    if(that.data.iscut){
      console.log('可以上传')
      callback(this.data.iscut&&file.type === 'image');
    }else{
      if(that.data.cutImgSrc=='back'){
        console.log('没有截图就返回')
        callback(this.data.iscut&&file.type === 'image');
      }else{
        console.log('刚上传没有截图,前往截图页面')
        that.setData({
          file
        })
        wx.navigateTo({
          url: '/test/pages/testpage/testpage?url='+file.thumb||url,
        })
      }
    }
  },
  // 上传封面
  posterup(event) {
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    const that = this
    if(!that.data.iscut){
      const { file } = event.detail;
      this.setData({file})
      that.setData({
        poster:[{status:'done',url:file.url}] 
      })
      wx.navigateTo({
        url: '/test/pages/testpage/testpage?url='+file.thumb||url,
      })
      return
    }
    let file = that.data.file
    file.url = that.data.cutImgSrc
    file.thumb = that.data.cutImgSrc
    that.setData({
      poster:[{status:'uploading',message: '正在上传'}] 
    })
    let token = wx.getStorageSync('token')
    // const uploadTask =
    wx.uploadFile({
      url: app.globalData.host+'VideoToken/file_img', 
      filePath: file.url,
      name: 'file',
      header:{
        "Content-Type": "multipart/form-data",
        'accept': 'application/json',
      },
      formData: { token,file },
      success(res) {
        that.setData({
          poster:[]
        })
        console.log(res)
        res = JSON.parse(res.data)
        console.log(res)
        if(res.code==5001||res.code==5000){
          wx.showToast({
            title: 'token已失效,请重新登录',
            icon:'none'
          })
          setTimeout(function(){
            wx.reLaunch({
              url: '/pages/personal/personal',
            })
          },1000)
          return
        }
        // 上传完成需要更新 fileList
        const { poster = [] } = that.data;
        
        poster.push({ 
          ...file, 
          url: res.data[0].set_path,
          urls: res.data[0].save_name,
          status:'done',
          message: '上传完成'
         });
        that.setData({ poster });
      },
      fail(err){
        console.log(err)
      }
    });
    // uploadTask.onProgressUpdate((res)=>{
    //   this.setData({
    //     progress:res.progress
    //   })
      // console.log('上传进度', res.progress)
      // console.log('已经上传的数据长度', res.totalBytesSent)
      // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    // })
  },
  // 删除图片
  delteImg(){
    this.setData({
      poster:[],
      iscut:false,
      file:{},
      cutImgSrc:''
    })
  },
  handleInput(e){
    let val = e.detail.value
    this.setData({
      title:val
    })
  },
  handleInput1(e){
    let val = e.detail.value
    this.setData({
      remark:val
    })
  },
  delteVideo(e){
    console.log(e)
    let index = e.detail.index
    this.data.fileList.splice(index,1)
  },
  submit(){
    let token = wx.getStorageSync('token')
    let filepath = this.data.fileList[0].url
    let fileimg = this.data.poster[0].urls
    let filetitle = this.data.title
    let remark = this.data.remark
    let user_img = this.data.userInfo.avatarUrl
    const that = this
    wx.request({
      url: app.globalData.host+'VideoToken/add',
      method:"POST",
      data:{
        filepath,
        filetitle,
        fileimg,
        remark,
        user_img,
        token
      },
      success(res){
        wx.showToast({
          title: res.data.msg,
        })
        if(res.data.code==5001||res.data.code==5000){
          wx.showToast({
            title: 'token已失效,请重新登录',
            icon:'none'
          })
          setTimeout(function(){
            wx.reLaunch({
              url: '/pages/personal/personal',
            })
          },2000)
          return
        }
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
        setTimeout(function(){
          wx.reLaunch({
            url: '/pages/myVideo/myVideo?upVideo='+that.data.upVideo,
          })
        },2000)
        if(res.data.code==2001){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }

      },
      fail(err){
        console.log(err)
      }
    })
  },
  changeVideo(){
    wx.redirectTo({
      url: '/pages/upload/upload?upVideo='+this.data.upVideo,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      upVideo:options.upVideo
    })
    wx.getUserInfo({
      success: res => {
        var userInfo = res.userInfo
        this.setData({
          userInfo
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   if(this.data.iscut){
      this.posterup()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})